/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.util.streamscanner;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.james.mime4j.MimeStreamParser;
import org.springframework.beans.factory.annotation.Required;

import com.googlecode.asyncmail.smtpserver.contenthandler.BannedAttachmentContentHandler;

public class BannedAttachmentStreamScanner implements StreamScanner {

    private List<String> bAttachments;

    private Log logger;

    @Required
    public void setBannedAttachments(List<String> bAttachments) {
        this.bAttachments = new ArrayList<String>();

        for (int i = 0; i < bAttachments.size(); i++) {
            this.bAttachments.add(bAttachments.get(i).toLowerCase());
        }
    }

    @Required
    public void setLogger(Log logger) {
        this.logger = logger;
    }

    /**
     * @see com.googlecode.asyncmail.util.streamscanner.StreamScanner#scan(java.io.InputStream)
     */
    public String scan(InputStream in) {
        BannedAttachmentContentHandler handler = new BannedAttachmentContentHandler();
        handler.setBannedAttachmentExtension(bAttachments);

        MimeStreamParser parser = new MimeStreamParser();
        parser.setContentHandler(handler);
        try {
            parser.parse(in);

            if (handler.isBannedAttachment()) {
                return "Banned attachment extension: "
                        + handler.getBannedExtension();
            }

        } catch (IOException e) {
            logger.error("Exception on parsing message: " + e);
        }

        return null;
    }

}
